package com.elcom.roaming.module.synthesis.lb.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public abstract class ClientService {
	
	public static final int UNKOWN_HOST = 1;
	public static final int IO_CONNECT_FAIL = 2;
	public static final int IO_CLOSE_FAIL = 3;
	public static final int IO_WRITE_FAIL = 4;
	
	private Socket socket;
	private InputStream is;
	private OutputStream os;

	protected String host;
	protected int port;

	public ClientService(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public boolean connect() {
		try {
			socket = new Socket(host, port);
			is = socket.getInputStream();
			os = socket.getOutputStream();
			return true;
		} catch (UnknownHostException e) {
			onError(UNKOWN_HOST, e);
		} catch (IOException e) {
			onError(IO_CONNECT_FAIL, e);
		}
		
		return false;
	}
	
	public int write(byte [] byteArray) {
		if (byteArray == null) return -1;
		if (byteArray.length == 0) return 0;
		
		try {
			os.write(byteArray);
			return byteArray.length;
		} catch (IOException e) {
			onError(IO_WRITE_FAIL, e);
		}
		
		return -1;
	}
	
	public int write(Object obj) {
		byte [] byteArray = toByteArray(obj);
		return write(byteArray);
	}
	
	public boolean close() {
		try {
			socket.close();
			return true;
		} catch (IOException e) {
			onError(IO_CLOSE_FAIL, e);
		}
		
		return false;
	}
	
	public boolean isConnected(){
		return socket.isConnected();
	}
	
	protected abstract void onError(int code, Throwable thw);
	
	protected abstract byte [] toByteArray(Object obj);
}
